// pages/school/detail/index.js
const {
  planCategory,
  planPage
} = require('../../api/api')
const {
  decodeUserInfo
} = require('../../api/login')
const {
  filterObj
} = require('../../utils/util')
const selectorRouteDatas = [{
    id: 0,
    title: "全国",
    type: "radiobox",
    key: "provinceId",
    items: []
  },
  {
    id: 1,
    title: "专业",
    type: "radiobox",
    key: "type",
    items: []
  },
  {
    id: 3,
    title: "本科",
    key: "level1Name",
    type: 'radiobox',
    items: [{
        id: '',
        title: "不限",
        checked: true
      }, {
        id: '本科',
        title: "本科",
      },
      {
        id: '专科（高职）',
        title: "专科（高职）",
      },

    ],
  },
  {
    id: 4,
    title: "时间",
    key: "year",
    type: 'radiobox',
    items: [],
  },


]
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectorDataList: selectorRouteDatas,
    selectedData: {
      provinceId: 0,
      type: '历史类',
      level1Name: '',
      year: 2022
    },
    isVip:false,
    pageSize:20,
    pageNo:1,
    searchName:'',
    tabIndex:0,
    filterRouteKey: "planFilters",
    currentRegion: {},
    placeholder:'请输入学校名称',
    province: {},
    cityList: [],
    planCategorydata:[],
    visible: false,
    tabData: [],
    total:0,
    columns: [{
        label: '学校',
        prop: 'schoolName',
        fontSize: '',
        width: '174',
        align: 'center',
        color: '#000000',
        padding: '20rpx'

      },
      {
        label: '批次',
        prop: 'localBatchName',
        fontSize: '',
        width: '112',
        align: 'center',
        padding: '0'
      },
      {
        label: '专业',
        prop: 'spname',
        fontSize: '',
        width: '282',
        align: 'center',
        padding: '20rpx'

      },
      {
        label: '人数',
        prop: 'num',
        fontSize: '',
        width: '82',
        align: 'center',
        padding: '0',
        isFilter:true

      }
    ],
    setting: {
      theadBgColor: 'transparent',
      theadColor: '#FBA300',
      theadFontWeight: '500',
      theadHeight: '80rpx',
      theadPadding: "0"
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const province = {
      value: wx.getStorageSync('userCitys').name,
      id: wx.getStorageSync('userCitys').code
    }
    this.setData({
      currentRegion: wx.getStorageSync('userCitys'),
      province
    })
    const {
      filterRouteKey,
      selectedData
    } = this.data
    wx.setStorageSync(filterRouteKey, selectedData)
    this.fetchCity()
    this.getPlanCategory()
  },
  async fetchCity() {
    const {
      type,
      selectorDataList,
      selectedData
    } = this.data
    const result=wx.getStorageSync('cityList')||await getApp().getCityList()
    const cityList=result.map((item)=>{
      return {
        id:item.id,
        value:item.title
      }
    })
    result.unshift({
      id: 0,
      title: '全国',
      checked: true
    })
    selectorDataList[0].items =result
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
     
    })
    this.setData({
      selectorDataList,
      cityList: cityList,
    })
    
  },
  confirm(e) {
    const {
      value,
      key
    } = e.detail
    // console.log(value.id)
    // console.log(this.data.province.id)
    
    if(value.id===this.data.province.id){
      this.filterKeyFunc()
      return 
    }
    this.setData({
      [key]: value
    })
    this.getPlanCategory()
  },
  filterKeyFunc() {
    const {
      filterRouteKey
    } = this.data
    const selectedData = wx.getStorageSync(filterRouteKey)
    const {
      selectorDataList,
      planCategorydata,
    } = this.data
    if(planCategorydata.length>0){
      var list = []
      planCategorydata.map((item) => {
        if (item.year == selectedData['year']) {
          list = item.list
          if (selectedData['year'] !== this.data.selectedData['year']) {
            selectedData['type'] = list[0].id
            wx.setStorageSync(filterRouteKey, selectedData)
          }
        }
      })
      selectorDataList[1].items = list
    }
 
    selectorDataList.map((item) => {
      const c = item.items.filter((child) => {
        return child.id == selectedData[item.key]
      })
      item.title = c.length > 0 ? c[0].title : item.title
     
    })
    this.setData({
      selectorDataList,
      selectedData
    })
    wx.setStorageSync(filterRouteKey, selectedData)
    this.onLoadFunc()
  },
  onLoadFunc() {
    this.setData({
      pageNo:1,
      tabData:[]
    })
    this.getPlanPage()
  },
  async onSelectChangedRoute(e) {
    wx.setStorageSync(this.data.filterRouteKey, {
      ...e.detail
    });
    this.setData({
      pageNo:1,
      tabData:[]
    })
    this.selectComponent("#tabData").show()
    this.filterKeyFunc()
  },

//  获取年份-类型
async getPlanCategory() {
  const {
    selectorDataList,
    filterRouteKey,
    selectedData,
    province
  } = this.data
  const params = {
    provinceId: province.id,
    schoolId: 0
  }
  const {
    result
  } = await planCategory(params)
  if (result.length > 0) {
    result.sort((a, b) => {
      return b.year - a.year
    }) //倒序
    result.map((item) => {
      item.list.map((e, i) => {
        let obj = {
          id: e,
          title: e
        }
        item.list[i] = obj
      })
    })
    var yearArr = result.map((item) => {
      return {
        id: item.year,
        title: item.year
      }
    })

    const {
      list
    } = result[0]
    selectedData.year = yearArr[0].id
    selectedData.type = list[0].id
    selectorDataList[3].items = yearArr
    selectorDataList[1].items = list
  }
  selectorDataList.map((item) => {
    const c = item.items.filter((child) => {
      return child.id == selectedData[item.key]
    })
    item.title = c.length > 0 ? c[0].title : item.title
  })
  this.setData({
    selectorDataList,
    selectedData,
    planCategorydata: result,
  })
  wx.setStorageSync(filterRouteKey, selectedData)
  this.onLoadFunc()
},
inputChange(e){
  this.setData({
    searchName:e.detail.value
  })
},
search(){
  this.onLoadFunc()
},
// 获取招生计划列表
async getPlanPage() {
  const {
    pageSize,
    pageNo,
    selectedData,
    province,
    tabIndex,
    searchName
  } = this.data
  let schoolName=''
  let spname=''
  tabIndex==0?schoolName=searchName:spname=searchName
  const {type,year,level1Name,provinceId}=selectedData
  let params = {
    pageSize,
    pageNo,
    schoolProvinceId:provinceId,
    type,
    year,
    level1Name,
  }
  tabIndex==0?params.schoolName=searchName:params.spname=spname
  params=filterObj(params)
  const {
    result
  } = await planPage(params)
  this.setData({
    tabData: this.data.tabData.concat(result.records),
    pageNo: pageNo + 1,
    total: result.total,
  })
  this.selectComponent("#tabData").hide('数据待更新~')
},
  toggle() {
    this.setData({
      visible: !this.data.visible
    })
  },
  changeIndex(e) {
    const {
      index,
      type
    } = e.currentTarget.dataset
    if(index==this.data.tabIndex)return
    this.setData({
      [type]: parseInt(index),
      searchName:'',
      placeholder:index==0?'请输入学校名称':'请输入专业名称'
    })
    this.onLoadFunc()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow(){
    this.fetchUserInfo()
  },
  async fetchUserInfo() {
    const {vipType}= await getApp().fetchUserInfo()
    this.setData({
       isVip:vipType,
   }) 
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const {tabData,total}=this.data
    if(tabData.length<total){
      this.getPlanPage()
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: '招生计划',
      imageUrl:'https://ehsimg.oss-cn-beijing.aliyuncs.com/images/static/users/shareImg.jpg'
    }
  }
})